(async function analyzeLostArkFinal() {
   const getStoveCookie = (n) => {
       const v = `; ${document.cookie}`;
       const p = v.split(`; ${n}=`);
       return p.length === 2 ? p.pop().split(";").shift() : null;
   };

   const YEARS = [2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026];
   let playTimeHTML = "";
   let chargeMethodStats = {};
   let grandTotal = 0;
   const yearlyData = {};

   const logBox = document.createElement('div');
   logBox.style.cssText = 'position:fixed;bottom:20px;right:20px;background:#2d3436;color:#00d2d3;padding:15px 20px;border-radius:12px;z-index:9999999;font-family:monospace;font-size:13px;max-width:320px;line-height:1.8;box-shadow:0 4px 20px rgba(0,0,0,0.3);';
   document.body.appendChild(logBox);
   const log = (msg) => logBox.innerHTML = msg;

   async function fetchPlayTime() {
       try {
           log('🕹️ 플레이시간 불러오는 중...');
           const t = getStoveCookie("SUAT");
           if (!t) { playTimeHTML = "<b style='color:#e74c3c;'>SUAT 없음</b>"; return; }
           const r = await fetch("https://api.onstove.com/game/v2.0/member/logs", { headers: { Authorization: `Bearer ${t}` } });
           const d = await r.json();
           const l = d.value.find(g => g.game_name === "LOST ARK");
           if (l) {
               const h = Math.floor(l.play_time / 60);
               const days = Math.floor(h / 24);
               const ty = Math.floor(days / 365);
               const rm = Math.floor((days % 365) / 30);
               playTimeHTML = `<div style="line-height:1.8;"><span style="color:#0984e3;font-weight:bold;">🕹️ 총 플레이시간:</span> <b>${h.toLocaleString()}시간</b><br><span style="color:#0984e3;font-weight:bold;">⏳ 시간 환산:</span> <b>${ty}년 ${rm}개월</b> (약 ${days.toLocaleString()}일)</div>`;
           }
       } catch (e) { playTimeHTML = "플레이 시간 로드 실패"; }
   }

   function cleanName(raw) {
       return raw
           .replace(/\s+/g, ' ')
           .replace(/(\[?[^\s\[\]]+\]?)?@[가-힣a-zA-Z0-9]+/g, '')
           .replace(/기간만료/g, '')
           .replace(/시작일\s*:\s*[\d\-:\s]+/g, '')
           .replace(/만료일\s*:\s*[\d\-:\s]+/g, '')
           .replace(/지급완료/g, '')
           .replace(/지급실패/g, '')
           .trim();
   }

   function getPackageBase(name) {
       // "패키지", "패스", "축복", "아크 패스" 등 묶음 상품 기준
       const match = name.match(/^(.+?(?:패키지|패스|축복\s*\[\d+일\]))\s*-?\s*/);
       return match ? match[1].trim() : null;
   }

   async function fetchChargeData() {
       for (const y of YEARS) {
           const range = { StartDate: `${y}.01.01`, EndDate: `${y}.12.31` };
           try {
               const cf = await $.ajax({ url: '/Cash/GetChargeList', data: { Page: 1, ...range } });
               const lastPage = parseInt($(cf).find('.pagination__last').attr('onClick')?.replace(/[^0-9]/g, '') || 1);
               for (let i = 1; i <= lastPage; i++) {
                   log(`💳 충전내역 ${y}년 ${i}/${lastPage} 페이지`);
                   const d = (i === 1) ? cf : await $.ajax({ url: '/Cash/GetChargeList', data: { Page: i, ...range } });
                   $(d).find('tbody tr').each((_, el) => {
                       const row = $(el);
                       const method = row.find('td:nth-child(2)').text().trim();
                       const amount = parseInt(row.find('td:nth-child(3)').text().replace(/[^0-9]/g, '')) || 0;
                       if (!method || method === '-' || amount === 0) return;
                       const methodKey = method.split(/[0-9]/)[0].trim();
                       grandTotal += amount;
                       chargeMethodStats[methodKey] = (chargeMethodStats[methodKey] || 0) + amount;
                   });
               }
           } catch (e) {}
       }
   }

   async function fetchPurchaseData() {
       for (const y of YEARS) {
           const range = { StartDate: `${y}.01.01`, EndDate: `${y}.12.31` };
           yearlyData[y] = { total: 0, items: {} };
           try {
               const cf = await $.ajax({ url: '/Cash/GetPurchaseList', data: { Page: 1, ...range } });
               const lastPage = parseInt($(cf).find('.pagination__last').attr('onClick')?.replace(/[^0-9]/g, '') || 1);
               for (let i = 1; i <= lastPage; i++) {
                   log(`🛒 구매내역 ${y}년 ${i}/${lastPage} 페이지`);
                   const d = (i === 1) ? cf : await $.ajax({ url: '/Cash/GetPurchaseList', data: { Page: i, ...range } });

                   $(d).find('tbody tr').each((_, el) => {
                       const row = $(el);
                       const amount = parseInt(row.find('td:nth-child(2)').text().replace(/[^0-9]/g, '')) || 0;
                       if (amount === 0) return;

                       // td[4] 안의 모든 상품명 텍스트 블록 추출
                       const td4 = row.find('td:nth-child(4)');
                       const allNames = [];

                       // 첫번째 직접 텍스트
                       const firstRaw = cleanName(td4.clone().children().remove().end().text());
                       if (firstRaw) allNames.push(firstRaw);

                       // 하위 div/span 안의 추가 상품명
                       td4.find('div, span').each((_, sub) => {
                           const subText = cleanName($(sub).text());
                           if (subText && !allNames.includes(subText) && subText.length > 2) {
                               allNames.push(subText);
                           }
                       });

                       if (allNames.length === 0) return;

                       const firstName = allNames[0];
                       const pkgBase = getPackageBase(firstName);
                       const displayName = pkgBase || firstName;

                       yearlyData[y].total += amount;

                       if (!yearlyData[y].items[displayName]) {
                           yearlyData[y].items[displayName] = { count: 0, amount: 0, subs: {} };
                       }
                       yearlyData[y].items[displayName].count += 1;
                       yearlyData[y].items[displayName].amount += amount;

                       // 하위항목 수집
                       if (pkgBase) {
                           allNames.forEach(n => {
                               const sub = n.replace(pkgBase, '').replace(/^\s*-\s*/, '').trim();
                               if (sub && sub !== pkgBase) {
                                   yearlyData[y].items[displayName].subs[sub] = (yearlyData[y].items[displayName].subs[sub] || 0) + 1;
                               }
                           });
                       }
                   });
               }
           } catch (e) {}
       }
   }

   await fetchPlayTime();
   await fetchChargeData();
   await fetchPurchaseData();

   log('🎨 화면 렌더링 중...');

   const methodHTML = Object.entries(chargeMethodStats)
       .sort((a, b) => b[1] - a[1])
       .map(([method, amt]) => `
           <div style="display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid #f0f0f0;">
               <span>💳 ${method}</span><b>${amt.toLocaleString()}원</b>
           </div>`).join('');

   const yearHTML = Object.keys(yearlyData).sort((a, b) => b - a).map(y => {
       const data = yearlyData[y];
       if (data.total === 0) return "";
       const itemRows = Object.entries(data.items)
           .sort((a, b) => b[1].amount - a[1].amount)
           .map(([name, info]) => {
               const subHTML = Object.keys(info.subs).length > 0 ? `
                   <div style="margin-top:4px;padding-left:12px;border-left:2px solid #dfe6e9;">
                       ${Object.entries(info.subs).map(([sub, cnt]) =>
                           `<div style="font-size:12px;color:#636e72;padding:2px 0;">· ${sub}${cnt > 1 ? ` x${cnt}` : ''}</div>`
                       ).join('')}
                   </div>` : '';
               return `
                   <div style="padding:8px 0;border-bottom:1px solid #eee;">
                       <div style="display:flex;justify-content:space-between;align-items:center;">
                           <span style="font-size:13px;flex:1;margin-right:10px;">${name}${info.count > 1 ? ` <span style="color:#e17055;font-weight:bold;">x${info.count}</span>` : ''}</span>
                           <b style="white-space:nowrap;">${info.amount.toLocaleString()}원</b>
                       </div>${subHTML}
                   </div>`;
           }).join('');
       return `
           <div style="margin-bottom:15px;border:1px solid #ccc;border-radius:12px;overflow:hidden;">
               <button onclick="const n=this.nextElementSibling;n.style.display=n.style.display==='none'?'block':'none'"
                   style="width:100%;padding:15px 25px;background:#2d3436;color:#fff;border:none;cursor:pointer;display:flex;justify-content:space-between;align-items:center;">
                   <span style="font-size:18px;font-weight:bold;">📅 ${y}년</span>
                   <span style="font-size:18px;color:#fdcb6e;font-weight:bold;">${data.total.toLocaleString()}원 ▾</span>
               </button>
               <div style="display:none;padding:15px;background:#fff;">${itemRows}</div>
           </div>`;
   }).join('');

   const layout = `
       <div id="loa-final" style="position:fixed;top:0;left:0;width:100%;height:100%;background:#f1f2f6;z-index:999999;overflow-y:auto;padding:30px 15px;font-family:sans-serif;box-sizing:border-box;color:#2d3436;">
           <div style="max-width:700px;margin:0 auto;">
               <div style="background:#fff;padding:20px 25px;border-radius:15px;margin-bottom:15px;border:1px solid #d1d9e0;">${playTimeHTML}</div>
               <div style="background:#2d3436;color:#fff;padding:25px;border-radius:15px;text-align:center;margin-bottom:15px;">
                   <div style="font-size:14px;opacity:0.8;margin-bottom:5px;">누적 총 결제액</div>
                   <div style="font-size:36px;font-weight:900;color:#00d2d3;">${grandTotal.toLocaleString()}원</div>
               </div>
               <div style="background:#fff;border-radius:15px;margin-bottom:20px;border:1px solid #d1d9e0;overflow:hidden;">
                   <button onclick="const n=this.nextElementSibling;n.style.display=n.style.display==='none'?'block':'none'"
                       style="width:100%;padding:18px 25px;background:#fff;border:none;cursor:pointer;display:flex;justify-content:space-between;font-weight:bold;font-size:16px;">
                       <span>💳 결제수단별 합계</span><span>보기 ▾</span>
                   </button>
                   <div style="display:none;padding:15px 25px;border-top:1px solid #eee;">${methodHTML}</div>
               </div>
               ${yearHTML}
               <div style="text-align:center;margin:30px 0;">
                   <button onclick="document.getElementById('loa-final').remove()"
                       style="padding:15px 50px;background:#333;color:#fff;border:none;border-radius:10px;cursor:pointer;font-weight:bold;">닫기</button>
               </div>
           </div>
       </div>`;

   document.body.insertAdjacentHTML('beforeend', layout);
   logBox.remove();
})();